require('es6-promise').polyfill();

import axios from 'axios'

export function loadUserCenters(data) {
  return {
    type: 'LOAD_USER_CENTER',
    data
  }
}


export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}

export function bindUserUnitAsync(data) {
  return function(dispatch) {
    return axios.post('/api/sysuser/updateUnits', data).then(
      resp => dispatch(loadUserCentersAsync()),
      error => dispatch(apiMsgAction(error.data.errMsg))
    )
  }
}

export function deleteUserUnitAsync(data) {
  return function(dispatch) {
    return axios.post('/api/sysuser/deleteUnit', data).then(
      resp => dispatch(loadUserCentersAsync()),
      error => dispatch(apiMsgAction(error.data.errMsg))
    )
  }
}

export function loadUserCentersAsync(data) {
  return function(dispatch) {
    return axios.post('/api/sysuser/me', data).then(
      resp => dispatch(loadUserCenters(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    )
  }
}

export function changeUserPasswordAsync(data) {
  return function(dispatch) {
    return axios.post('/api/sysuser/changePassword', data)
    .then(function(response) {
      if (response.data.success) {
        dispatch(apiMsgAction("提交成功"))
      }
      else {
        dispatch(apiMsgAction(response.data.errMsg))
      }
    })
    .catch(function(error) {
      dispatch(apiMsgAction(error.data.errMsg))
    })
  }
}
